package com.yuanfeng.authserver.filter;

import com.alibaba.fastjson.JSON;
import com.yuanfeng.authserver.entity.LoginUser;
import com.yuanfeng.commoms.config.RedisCache;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.exception.DefinedException;
import com.yuanfeng.commoms.util.JwtUtil;
import com.yuanfeng.commoms.util.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid=null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            // 交给全局异常处理类处理
            resolver.resolveException(request, response, null, new DefinedException(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg()));

            return;



        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        String value= RedisUtil.get(redisKey);
        LoginUser loginUser= JSON.parseObject(value,LoginUser.class);
       // LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){

            resolver.resolveException(request, response, null, new DefinedException(BizCodeEnume.USER_IS_NOT_LOGGED_IN.getCode(), BizCodeEnume.USER_IS_NOT_LOGGED_IN.getMsg()));
            return;
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}

